//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Microsoft.Practices.Prism.Commands;
using P2.Cuberry.Framework.Helper;
using Microsoft.Practices.Prism.Events;
using P2.Cuberry.Framework.Helper.Configuration;


namespace P2.Cuberry.Modules.SimpleAccounting.FiCheque
{
    public class FiChequesDetailsPresentationModel : INotifyPropertyChanged, IDisposable, IDataErrorInfo
    {

        public FiChequesDetailsPresentationModel(IFiChequesDetailsView view, BusinessEntities.FiCheque model, Services.IFiChequeService service, 
            IEventAggregator eventAggregator)
        {
            try
            {
                View = view;
                this.Model = model;
                this.Service = service;
                this.eventAggregator = eventAggregator;
                

                //DDL++
                //added  by wli 30-5-2012
                if (Model != null)
                {
                    if (Model.FiChequeID > 0)
                    {
                        BusinessEntities.FiCheque objdata = new BusinessEntities.FiCheque();
                        this.DebitTransactionItems = objdata.GetDataofTransactionitem(model.FiChequeID, false);
                        this.CreditTransactionItems = objdata.GetDataofTransactionitem(model.FiChequeID, true);
                    }
                }
                //end
                this.XConfigCurrencys = BusinessEntities.XConfigCurrency.GetList;
                this.FiscalYears = P2.Cuberry.Modules.SimpleAccounting.FiAccount.BusinessEntities.FiFiscalYear.GetList;
               
                if (this.FiscalYears.Count > 0 && model.FiscalYearID <= 0)
                    this.Model.FiscalYearID = this.FiscalYears[0].FiscalYearID;
                if (!this.Model.CurrencyID.HasValue)
                {
                    string currIdstr = P2.Cuberry.Framework.Helper.Configuration.ConfigurationSetUp.GetAppConfigValue("FiChequeDefaultCurrency");
                    if (!string.IsNullOrEmpty(currIdstr))
                    {
                        int currId;
                        if (int.TryParse(currIdstr, out currId))
                            this.Model.CurrencyID = currId;
                    }
                }

                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "FiChequesDetailsView");
                MessageStack = new P2MessageStack();
                View.Model = this;

                this.FiChequeSaveCommand = new DelegateCommand<object>(OnFiChequeSaveExecute, OnFiChequeSaveCanExecute);
                this.FiChequeCloseCommand = new DelegateCommand<object>(OnFiChequeCloseExecute, OnFiChequeCloseCanExecute);
                
                this.FiChequeCancelCommand = new DelegateCommand<object>(OnFiChequeCancelExecute, OnFiChequeCancelCanExecute);
                this.FiChequePaidCommand = new DelegateCommand<object>(OnFiChequePaidExecute, OnFiChequePaidCanExecute);
                this.FiChequeReOpenCommand = new DelegateCommand<object>(OnFiChequeReOpenExecute, OnFiChequeReOpenCanExecute);
                this.FiChequeOpenTransactionCommand = new DelegateCommand<object>(OnFiChequeOpenTransactionExecute, OnFiChequeOpenTransactionCanExecute);

                this.FiChequeTransferCommand = new DelegateCommand<object>(OnFiChequeTransferExecute, OnFiChequeTransferCanExecute);

                this.InfoCommand = new DelegateCommand<object>(OnInfoExecute, OnInfoCanExecute);
                this.HistoryCommand = new DelegateCommand<object>(OnHistoryExecute, OnHistoryCanExecute);
                
                this.RefreshView();
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        #region Members

        public int ChequeID
        {
            get { return Model.FiChequeID; }
        }

        //Add++

        public int FiscalYearID 
        {
            get { return Model.FiscalYearID; }
            set
            {
                if (value != Model.FiscalYearID)
                {
                    Model.FiscalYearID = value;
                    OnPropertyChanged("FiscalYearID");
                }
            }
        }

        
        public decimal? ChequeNo //check if nullable? 
        {
            get { return Model.ChequeNo; }
            set
            {
                if (value != Model.ChequeNo)
                {
                    Model.ChequeNo = value;
                    OnPropertyChanged("ChequeNo");
                }
            }
        }

        public string Bank //check if nullable? 
        {
            get { return Model.Bank; }
            set
            {
                if (value != Model.Bank)
                {
                    Model.Bank = value;
                    OnPropertyChanged("Bank");
                }
            }
        }

        public string MyBank //check if nullable? 
        {
            get { return Model.MyBank; }
            set
            {
                if (value != Model.MyBank)
                {
                    Model.MyBank = value;
                    OnPropertyChanged("MyBank");
                }
            }
        }
        public DateTime? ValueDate //check if nullable? 
        {
            get { return Model.ValueDate; }
            set
            {
                if (value != Model.ValueDate)
                {
                    Model.ValueDate = value;
                    OnPropertyChanged("ValueDate");
                }
            }
        }

        public decimal? Amount //check if nullable? 
        {
            get { return Model.Amount; }
            set
            {
                if (value != Model.Amount)
                {
                    Model.Amount = value;
                    OnPropertyChanged("Amount");
                }
            }
        }

        public int? FiTransactionID //check if nullable? 
        {
            get { return Model.FiTransactionID; }
            set
            {
                if (value != Model.FiTransactionID)
                {
                    Model.FiTransactionID = value;
                    OnPropertyChanged("FiTransactionID");
                }
            }
        }

   
        public string Note //check if nullable? 
        {
            get { return Model.Note; }
            set
            {
                if (value != Model.Note)
                {
                    Model.Note = value;
                    OnPropertyChanged("Note");
                }
            }
        }


       
        //DDL++

        public int CurrencyID //check if nullable? 
        {
            get { return Model.CurrencyID.GetValueOrDefault(-1); }
            set
            {
                if (value != Model.CurrencyID)
                {
                    if (value == -1)
                        Model.CurrencyID = null;
                    else
                        Model.CurrencyID = value;
                    OnPropertyChanged("CurrencyID");
                }
            }
        }

        //added by wli   29-5-2012

        //public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> CreditTransactionItems
        //{
        //    get
        //    {
        //        return Model.CredittransactionItem;
        //    }
        //}
        //public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> DebitTransactionItems
        //{
        //    get
        //    {
        //        return Model.DebitttransactionItem;
        //    }
        //}

        //public decimal DebitTransactionSum
        //{
        //    get
        //    {
        //        return Model.DebitTransactionSum;
        //    }
        //}


        //public decimal CreditTransactionSum
        //{
        //    get
        //    {
        //        return Model.CreditTransactionSum;
        //    }
        //}




        public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> CreditTransactionItems { get; set; }

        public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> DebitTransactionItems { get; set; }


        public decimal DebitTransactionSum
        {
            get
            {
                if (DebitTransactionItems != null && DebitTransactionItems.Count > 0)
                {
                    decimal summary = 0;
                    foreach (var tempItem in DebitTransactionItems)
                    {
                        if (tempItem.FiTransactionItemAdd == true)
                        {
                            summary += tempItem.FiAccountAmountDebit;
                        }
                    }

                    return summary;
                }
                else
                {
                    return 0;
                }
            }

        }


        public decimal CreditTransactionSum
        {
            get
            {
                if (CreditTransactionItems != null && CreditTransactionItems.Count > 0)
                {
                    decimal summary = 0;
                    foreach (var tempItem in CreditTransactionItems)
                    {
                        if (tempItem.FiTransactionItemAdd == true)
                        {
                            summary += tempItem.FiAccountAmountCredit;
                        }
                    }
                    return summary;
                }
                else
                {
                    return 0;
                }
            }
        }




        #endregion


        #region Computed Members

        public string StatusName
        {
            get { return Model.CurrentStatus.StatusNameCur; }
        }

        public bool ModelIsModified
        {
            get
            {
                return Model.Modified;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                P2.Cuberry.Framework.Security.User.ControlRight controlRight;
                if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                    return !controlRight.IsActive;
                else
                    return true;
            }
        }

        public bool IsEditable
        {
            get
            {
                return !IsReadOnly;
            }
        }

        #endregion


        #region Reference Tables

        //DDL++
        public List<BusinessEntities.XConfigCurrency> XConfigCurrencys { get; set; }
        public List<P2.Cuberry.Modules.SimpleAccounting.FiAccount.BusinessEntities.FiFiscalYear> FiscalYears { get; set; }

        //public List<P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus> WorkflowStatusses { get; set; }

        #endregion


        #region Commands

        public DelegateCommand<object> FiChequeSaveCommand { get; set; }
        public DelegateCommand<object> FiChequeCloseCommand { get; set; }
        public DelegateCommand<object> FiChequePrintCommand { get; set; }        
        public DelegateCommand<object> FiChequeCancelCommand { get; set; }
        public DelegateCommand<object> FiChequePaidCommand { get; set; }
        public DelegateCommand<object> FiChequeReOpenCommand { get; set; }
        public DelegateCommand<object> FiChequeOpenTransactionCommand { get; set; }
        public DelegateCommand<object> FiChequeTransferCommand { get; set; }

        public DelegateCommand<object> InfoCommand { get; set; }
        public DelegateCommand<object> HistoryCommand { get; set; }


        void OnFiChequeSaveExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            this.Save();
            this.RefreshView();
            return;
        }

        bool OnFiChequeSaveCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnFiChequeCloseExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                View.Close();
            }
        }

        bool OnFiChequeCloseCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }
                       

        void OnFiChequeCancelExecute(object sourceObj)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                MessageStack.Clear();
                MessageStack.Add(new P2TransactionMessage(P2ValidationStatus.yellow, ""));
                if (View.YellowStatusWarning(P2Translator.GetResource("fiChequeCancelConfirmation"), P2Translator.GetResource("TMsg_Warning")))
                {
                    MessageStack.Clear();
                    this.Model.Cancel();
                }
                else
                    MessageStack.Clear();

                
                this.RefreshView();

            }
        }


        bool OnFiChequeCancelCanExecute(object sourceObj)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeCancelBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnFiChequePaidExecute(object sourceObj)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                this.Model.Paid();
                this.RefreshView();

            }
        }

        bool OnFiChequePaidCanExecute(object sourceObj)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequePaidBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }


        void OnFiChequeReOpenExecute(object sourceObj)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                this.Model.ReOpen();
                this.RefreshView();
            }
        }

        bool OnFiChequeReOpenCanExecute(object sourceObj)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeReOpenBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnFiChequeOpenTransactionExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            if (this.View.AskSave())
            {
                View.Close();
                var checkEvent = eventAggregator.GetEvent<P2Event>();
                P2EventParameter eventPar = new P2EventParameter();
                eventPar.Name = "FiTransactionItem_OpenTransaction";
               // eventPar.Parameters["FiTransactionItemID"] = this.FiTransactionID.ToString();

                //added by wli 29-5-2012
                eventPar.Parameters["FiTransactionItemID"] = sourceAccount.ToString();
                //end
                checkEvent.Publish(eventPar);
            }
        }

        bool OnFiChequeOpenTransactionCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeOpenTransactionBtn", out controlRight))
                return controlRight.IsActive && this.FiTransactionID.HasValue && !this.IsOpenedFromTransaction;
            else
                return false;
        }


        bool OnFiChequeTransferCanExecute(object sourceObj)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeTransferBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnFiChequeTransferExecute(object sourceObj)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                this.Model.Transfer();
                this.RefreshView();

            }
        }

        void OnInfoExecute(object sourceItem)
        {
            Model.GetObjectInfo();
            return;
        }
        
        bool OnInfoCanExecute(object sourceItem)
        {
            return true;
        }


        bool OnHistoryCanExecute(object sourceItem)
        {
            return true;
        }
        
        void OnHistoryExecute(object sourceItem)
        {
            Model.GetObjectHistory("FiCheque", "FiCheque", this.Model.FiChequeID);
            return;
        }

        //Add++
        public void RefreshView()
        {
            try
            {
                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "FiChequesDetailsView");
                OnPropertyChanged("FiChequeID");
                OnPropertyChanged("FiscalYearID");
                OnPropertyChanged("ChequeNo");
                OnPropertyChanged("Bank");
                OnPropertyChanged("MyBank");
                OnPropertyChanged("ValueDate");
                OnPropertyChanged("Amount");
                OnPropertyChanged("FiTransactionID");
                OnPropertyChanged("Note");

                //Standard Fields
                OnPropertyChanged("StatusName");

                this.FiChequeCloseCommand.RaiseCanExecuteChanged();
                this.FiChequeSaveCommand.RaiseCanExecuteChanged();
                this.FiChequeCancelCommand.RaiseCanExecuteChanged();
                this.FiChequePaidCommand.RaiseCanExecuteChanged();
                this.FiChequeReOpenCommand.RaiseCanExecuteChanged();
                this.FiChequeOpenTransactionCommand.RaiseCanExecuteChanged();
                this.FiChequeTransferCommand.RaiseCanExecuteChanged();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        public bool Save()
        {
            bool isNewItem = (this.ChequeID <= 0);
            MessageStack.Clear();
            Model.InsertAndUpdate(MessageStack, true);

            if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red && !Model.Modified)
            {
                return true;
            }
            else
                return false;

        }


        //Find++
        public ObservableCollection<BusinessEntities.FiCheque> GetCheques()
        {
            ObservableCollection<BusinessEntities.FiCheque> _myItemDT = Service.RetrieveCheques();
            var ordered = _myItemDT; //.OrderBy(f => f.FirstNameEn); --->>> If they have to be sorted!
            ObservableCollection<BusinessEntities.FiCheque> result = new ObservableCollection<BusinessEntities.FiCheque>();

            foreach (var xItem in ordered)
            {
                result.Add(xItem);
            }
            return result;
        }

        #endregion


        #region Model & View Components

        public IFiChequesDetailsView View { get; set; }

        public Services.IFiChequeService Service;
        public BusinessEntities.FiCheque Model { get; set; }
        public Dictionary<string, P2.Cuberry.Framework.Security.User.ControlRight> ControlRights;
        private IEventAggregator eventAggregator;
        public bool IsOpenedFromTransaction = false;
        protected P2MessageStack myMessageStack = new P2MessageStack();
        public P2MessageStack MessageStack
        {
            get
            {
                return myMessageStack;
            }
            set
            {
                myMessageStack = value;
                OnPropertyChanged("MessageStack");
            }
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion


        #region IDisposable Members

        public void Dispose()
        {
            if (View != null)
                View.Model = this;
            View = null;
            this.Model = null;
            this.Service = null;
        }

        #endregion


        #region Error Handling

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string result = null;

                P2MessageStack propertyMessageStack = this.Model.Validator.ValidateProperty(this.Model, columnName);
                if (propertyMessageStack != null && propertyMessageStack.Count > 0)
                {
                    foreach (P2TransactionMessage message in propertyMessageStack)
                    {
                        if (message.TransactionStatus != "green")
                        {
                            if (result == null)
                                result = message.MessageText;
                            else
                                result += "\n" + message.MessageText;
                        }
                    }
                }
                return result;
            }
        }

        #endregion


    }
}

